﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace FishServe.Build.Common
{
    public class SolutionBuildConfig
    {
        public string DeploymentDir { get; set; }
        public string FileHashAlgorithm { get; set; }
        public List<ReleaseSet> ReleaseSets { get; set; }

        public SolutionBuildConfig()
        {
            ReleaseSets = new List<ReleaseSet>();
        }

        public static SolutionBuildConfig Load(string filename)
        {
            SolutionBuildConfig buildConfig = new SolutionBuildConfig(); ;

            XDocument configDoc = XDocument.Load(filename);

            buildConfig.DeploymentDir = configDoc.Element("PublishConfig").Attribute("DeploymentDir").Value;
            buildConfig.FileHashAlgorithm = configDoc.Element("PublishConfig").Attribute("FileHashAlgorithm").Value;

            XElement[] releaseSets = configDoc.Element("PublishConfig").Element("ReleaseSets").Elements("ReleaseSet").ToArray<XElement>();
            foreach (XElement releaseSetElement in releaseSets)
            {
                ReleaseSet releaseSet = new ReleaseSet();
                releaseSet.Name = releaseSetElement.Attribute("Name").Value;
                releaseSet.Version = releaseSetElement.Attribute("Version").Value;
                releaseSet.Type = releaseSetElement.Attribute("Type").Value;
                XElement[] modules = releaseSetElement.Element("Modules").Elements("Module").ToArray<XElement>();
                foreach (XElement moduleElement in modules)
                {
                    ReleaseSetModule module = new ReleaseSetModule();
                    module.Name = moduleElement.Attribute("ModuleName").Value;
                    releaseSet.Modules.Add(module);
                }

                XElement associatedReleaseSetsElement = releaseSetElement.Element("AssociatedReleaseSets");
                if (associatedReleaseSetsElement != null)
                {
                    XElement[] associatedReleaseSetElements = associatedReleaseSetsElement.Elements("ReleaseSet").ToArray<XElement>();
                    foreach (XElement associatedReleaseSetElement in associatedReleaseSetElements)
                    {
                        ReleaseSet associatedReleaseSet = new ReleaseSet();
                        associatedReleaseSet.Name = associatedReleaseSetElement.Attribute("Name").Value;
                        releaseSet.AssociatedReleaseSets.Add(associatedReleaseSet);
                    }
                }

                buildConfig.ReleaseSets.Add(releaseSet);
            }

            return buildConfig;
        }
    }
}
